# -*- coding: utf-8 -*-

'''
Created on 16.08.2011

@author: Vlasov A. I. <root@proscript.ru>
'''
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect

from okno.forms import CategoryForm, ServiceForm, DocumentForm, StatementForm
from okno.models import Service, Document, Statement, Citizen

from util.template import render_by_request_context

@login_required
def create(request, id):
    if request.method == 'GET':
        try:
            citizen = Citizen.objects.get(id=id)
        except:
            return HttpResponseRedirect(u'/okno/search/')
        
        request.session['citizen'] = int(id)
        try:
            del request.session['statement']
        except Exception:
            pass
        
        cats_form = CategoryForm()
        
        old_statements = Statement.objects.filter(asp_citizen=citizen)
        
        return render_by_request_context(request, 'okno/main.html', {
                                                    'cats': cats_form,
                                                    'citizen': citizen,
                                                    'old_statements': old_statements, })
    
    return HttpResponseRedirect(u'/okno/search/')

@login_required
def edit(request, id):
    if request.method == 'GET':
        try:
            statement = Statement.objects.get(id=id)
        except:
            return HttpResponseRedirect(u'/okno/search/')
        
        
        request.session['citizen'] = statement.citizen.id
        request.session['statement'] = statement
        
        cats_form = CategoryForm(initial={'categories': statement.categories.all(), 'id': id})
        
        old_statements = {} #Statement.objects.filter(citizen=citizen)
        
        return render_by_request_context(request, 'okno/main.html', {
                                                    'cats': cats_form,
                                                    'citizen': statement.citizen,
                                                    'old_statements': old_statements, })
    return HttpResponseRedirect(u'/okno/search/')

@login_required
def services(request):
    if request.method == 'POST' and request.session.has_key('citizen'):
        
        try:
            citizen = Citizen.objects.get(id=request.session['citizen'])
        except:
            return HttpResponseRedirect(u'/okno/search/')
            
        cats_form = CategoryForm(request.POST)
            
        if cats_form.is_valid():
            id = cats_form.cleaned_data['id']
            try:
                statement = Statement.objects.get(id=id)
                
                services_form = ServiceForm(initial={
                    'id': statement.id,
                    'categories': request.POST.getlist('categories'),
                    'services': [service['id'] for service in Service.objects.filter(id__in=statement.services.all).values('id')],
                })
            except Exception:
                services_form = ServiceForm(request.POST)
    
            return render_by_request_context(request, 'okno/main.html', {'srvs': services_form,
                                                                             'citizen': citizen, })
        
        return create(request, request.session['citizen'])
        
    return HttpResponseRedirect(u'/okno/search/')

@login_required
def documents(request):
    if request.method == 'POST' and request.session.has_key('citizen'):
        try:
            citizen = Citizen.objects.get(id=request.session['citizen'])
        except:
            return HttpResponseRedirect(u'/okno/search/')
        
        services_form = ServiceForm(request.POST)
        
        if services_form.is_valid():
            id = services_form.cleaned_data['id']
            try:
                statement = Statement.objects.get(id=id)
                
                documents_form = DocumentForm(initial={
                    'id': statement.id,
                    'categories': request.POST.getlist('categories'),
                    'services': request.POST.getlist('services'),
                    'documents': [document['id'] for document in Document.objects.filter(id__in=statement.documents.all).values('id')],
                })
            except Exception:
            #request.session['services'] = services_form.cleaned_data['services']
            
                documents_form = DocumentForm(request.POST)
            
            return render_by_request_context(request, 'okno/main.html', {'docs': documents_form,
                                                                         'citizen': citizen, })
        
        return services(request)
    
    return HttpResponseRedirect(u'/okno/search/')
    
    
@login_required
def final(request):
    if request.method == 'POST' and request.session.has_key('citizen'):
        
        try:
            citizen = Citizen.objects.get(id=request.session['citizen'])
        except Exception:
            return HttpResponseRedirect(u'/okno/search/')
        
        documents_form = DocumentForm(request.POST)
        
        if documents_form.is_valid():
            id = documents_form.cleaned_data['id']
            
            try:
                statement = Statement.objects.get(id=id)
            except Exception:
                statement = None
            
            if request.POST.has_key(u'number'):
                
                statement_form = StatementForm(request.POST, instance=statement)
                
                if statement_form.is_valid():
                    if statement:
                        try:
                            assert(statement.user == request.user)
                            #cats = [unicode(st.id) for st in statement.categories.all()]
                            #assert(request.POST.getlist('categories') == cats)
                            #svcs = [unicode(st.id) for st in statement.services.all()]
                            #assert(request.POST.getlist('services') == svcs)
                            #docs = [unicode(st.id) for st in statement.documents.all()]
                            #assert(request.POST.getlist('documents') == docs)   
                        except AssertionError:
                            statement_form.instance.pk = None
                            statement_form.set_new_instance_number()
                            
                        del request.session['statement']
                    
                    statement = statement_form.save(commit=False)
                    
                    statement.user = request.user
                    statement.asp_citizen = citizen
                    
                    statement.save()
                    statement_form.save_m2m()
                    
                    del request.session['citizen']
                    
                            
                    if request.POST.has_key(u'_save_and_print'):
                        return HttpResponseRedirect(u'/okno/print/%i/'%statement.id)
                            
                    return HttpResponseRedirect(u'/okno/view/%i/'%statement.id)
                    
            else:
                statement_form = StatementForm(initial = {
                    'categories': request.POST.getlist('categories'),
                    'services': request.POST.getlist('services'),
                    'documents': request.POST.getlist('documents'),
                    'phone': citizen.phone,
                }, instance=statement)
                
            return render_by_request_context(request, 'okno/main.html', {'form' : statement_form, 
                                                                         'citizen': citizen,
                                                                         'id': id })
        
        return documents(request)
    
    return HttpResponseRedirect(u'/okno/search/')

def update_inflections(request, id):
    try:
        statement = Statement.objects.get(id=id)
    except Statement.DoesNotExist:
        return HttpResponseRedirect('/okno/search/')
    
    
    if statement.regen_inflections():
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    
    
    #TODO: как-то выводить сообщение об ошибке
    return HttpResponseRedirect(request.META['HTTP_REFERER'])
        